package com.xiaojiu.base;

import android.os.Bundle;
import android.support.annotation.Nullable;

import java.lang.reflect.ParameterizedType;

/**
 * Author: Othershe
 * Time:  2016/8/11 17:53
 */
public abstract class BaseMvpActivity<V, P extends BasePresenter<V>> extends BaseActivity {
    protected P mPresenter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mPresenter = get(this, 1);
        mPresenter.attach((V) this, this);
        super.onCreate(savedInstanceState);
    }

    /**
     * @param o        带泛型对象
     * @param position 泛型的位置
     * @param <T>      返回示例类型
     * @return
     */
    private <T> T get(Object o, int position) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass()
                    .getGenericSuperclass())).getActualTypeArguments()[position])
                    .newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        mPresenter.detach();
        super.onDestroy();
    }
}